package cn.wolfcode.crm.serivce.impl;

import cn.wolfcode.crm.domain.Menu;
import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.serivce.IRoleService;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;


@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper mapper;

    @Override
    public void deleteByPrimaryKey(Long id) {
        mapper.deleteRelation(id);
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void saveOrUpdate(Role record) {
        if (record.getId() == null) {
            //保存操作
            mapper.insert(record);
        }else {
            //更新前删除原有的
            mapper.deleteRelation(record.getId());
            mapper.deleteMenuRelation(record.getId());
            mapper.updateByPrimaryKey(record);
        }
        //添加权限关系
        for (Permission permission : record.getPermissions()) {
            mapper.insertRelation(record.getId(),permission.getId());
        }
        //添加菜单关系
        for (Menu menu : record.getMenus()) {
            mapper.insertMenuRelation(record.getId(),menu.getId());
        }
    }

    @Override
    public Role selectByPrimaryKey(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> selectAll() {
        return mapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject qo) {
        Integer total = mapper.count(qo);
        if (total > 0) {
            List<Role> rows = mapper.query(qo);

            return new PageResult(total,rows);
        }
        return new PageResult(0, Collections.EMPTY_LIST);
    }
    //员工编辑--角色回显
    @Override
    public List<Long> selectByEmployeeId(Long employeeId) {
        return mapper.selectByEmployeeId(employeeId);
    }

    @Override
    public List<String> selectNameByEmployeeId(Long id) {
        return mapper.selectNameByEmployeeId(id);
    }
}
